package com.ruoyi.monitor.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dyun.tool.mybatis.domain.PageDomain;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.enums.BusinessTypeEnum;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.support.DateRange;
import com.ruoyi.project.monitor.entity.SysLoginLog;
import com.ruoyi.project.monitor.service.ISysLoginLogService;
import lombok.AllArgsConstructor;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.$;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * 登陆日志 控制层
 *
 * @author dy
 */
@RestController
@RequestMapping("/monitor/loginlog")
@AllArgsConstructor
public class SysLoginLogController extends BaseController {

    private final ISysLoginLogService sysLoginLogService;

    /**
     * 分页
     */
    @PreAuthorize("@ss.hasPermi('monitor:loginlog:list')")
    @GetMapping("/list")
    public R<IPage<SysLoginLog>> list(SysLoginLog sysLoginLog, PageDomain pageDomain, DateRange dateRange) {
        IPage<SysLoginLog> pages = sysLoginLogService.page(startPage(pageDomain), buildQueryWrapper(sysLoginLog, dateRange));
        return success(pages);
    }

    /**
     * 删除
     */
    @SysLog(title = "登陆日志", businessType = BusinessTypeEnum.DELETE)
    @PreAuthorize("@ss.hasPermi('monitor:loginlog:remove')")
    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable Long[] ids) {
        return status(sysLoginLogService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 条件删除
     */
    @SysLog(title = "登陆日志", businessType = BusinessTypeEnum.CLEAN)
    @PreAuthorize("@ss.hasPermi('monitor:loginlog:remove')")
    @DeleteMapping("/clean")
    public R clean(SysLoginLog sysLoginLog, DateRange dateRange) {
        return status(sysLoginLogService.remove(buildQueryWrapper(sysLoginLog, dateRange)));
    }

    private Wrapper<SysLoginLog> buildQueryWrapper(SysLoginLog sysLoginLog, DateRange dateRange) {
        return new LambdaQueryWrapper<SysLoginLog>()
                .like($.isNotBlank(sysLoginLog.getIpaddr()), SysLoginLog::getIpaddr, sysLoginLog.getIpaddr())
                .eq($.isNotNull(sysLoginLog.getStatus()), SysLoginLog::getStatus, sysLoginLog.getStatus())
                .eq($.isNotNull(sysLoginLog.getUserType()), SysLoginLog::getUserType, sysLoginLog.getUserType())
                .like($.isNotBlank(sysLoginLog.getUserName()), SysLoginLog::getUserName, sysLoginLog.getUserName())
                .between($.isAnyNotBlank(dateRange.getBeginTime(), dateRange.getEndTime()), SysLoginLog::getOperTime, dateRange.getBeginTime(), dateRange.getEndTime());
    }
}
